using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Experiments2D.Bublz;
using Common.Particles;
using Common.Utils;
using Common.Exp2D;

namespace Experiments2D
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class BublzGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;        
        
        RenderTarget2D m_shaderRenderTarget;
        Texture2D m_shaderTexture;
        Object2D m_cursor;
                
        float m_waveFreqValue;
        float m_waveHeightValue = 1;
        EffectParameter m_waveFreqParam;
        EffectParameter m_waveHeightParam;
        Effect m_effects;

        float m_centerValue;
        bool m_inc = true;
        float m_blurAmountInc = 0;
        

        float m_rippleProgress = 0;
        float m_rippleX;
        float m_rippleY;
        bool m_effectOn = false;
        
        float m_angleValue;
        EffectParameter m_centerParam;
        EffectParameter m_blurAmountParam;

        EffectParameter m_rippleProgressParam;
        EffectParameter m_rippleCoordXParam;
        EffectParameter m_rippleCoordYParam;

        EffectParameter m_angleParam;

        Board2D m_bubblzBoard;

        public BublzGame()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 600;
            graphics.PreferredBackBufferHeight = 800;
            graphics.ApplyChanges();
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            //IsMouseVisible = true;
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            m_bubblzBoard = new Board2D(Content, new Vector2(20, 0), 800, 600 , 8, 15, 20);
            MouseState ms = Mouse.GetState();
            m_cursor = new Object2D(Content.Load<Texture2D>("Texture/Objects/Misc/Arrow3"), new Vector2(ms.X, ms.Y), true);            
            InitEffects();
            InitShaderRenderTarget();

            
        }

        private void InitShaderRenderTarget()
        {
            m_shaderRenderTarget = GameGraphicsUtils.CloneRenderTarget(GraphicsDevice, 1);
            m_shaderTexture = new Texture2D(GraphicsDevice, m_shaderRenderTarget.Width, m_shaderRenderTarget.Height, false, m_shaderRenderTarget.Format);
        }

        private void InitEffects()
        {            
            m_effects = Content.Load<Effect>("Effects");
            m_waveFreqParam = m_effects.Parameters["frequency"];
            m_waveHeightParam = m_effects.Parameters["height"];

            m_centerParam = m_effects.Parameters["center"];
            m_blurAmountParam = m_effects.Parameters["blurAmount"];
            m_angleParam = m_effects.Parameters["angle"];

            m_rippleProgressParam = m_effects.Parameters["rippleProgress"];

            m_rippleCoordXParam = m_effects.Parameters["rippleCoordX"];
            m_rippleCoordYParam = m_effects.Parameters["rippleCoordY"];
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            

            HandleMouseInput(gameTime);
            //HandleKeyBoardInput(gameTime);

            UpdateEffectParams(gameTime);

            m_bubblzBoard.Update(gameTime);            
            
            base.Update(gameTime);
        }

        private void UpdateEffectParams(GameTime gameTime)
        {            
            m_waveFreqValue += (float)gameTime.ElapsedGameTime.TotalSeconds;
            m_waveHeightValue -= (float)gameTime.ElapsedGameTime.TotalSeconds * 0.1f;
            m_waveFreqParam.SetValue(m_waveFreqValue);
            m_waveHeightParam.SetValue(m_waveHeightValue);

            m_centerParam.SetValue(0.5f);
            if (m_rippleProgress < 1 && m_bubblzBoard.Ripple)
            {
                m_rippleX = m_bubblzBoard.RipplePos.X / (float)Window.ClientBounds.Width;
                m_rippleY = m_bubblzBoard.RipplePos.Y / (float)Window.ClientBounds.Height;
                m_rippleProgress += (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            else
            {
                m_bubblzBoard.Ripple = false;
                m_rippleProgress = 0;
            }

            if (m_rippleProgress > 0 && !m_bubblzBoard.Ripple)
            {
                m_rippleX = m_bubblzBoard.RipplePos.X / (float)Window.ClientBounds.Width;
                m_rippleY = m_bubblzBoard.RipplePos.Y / (float)Window.ClientBounds.Height;
                m_rippleProgress -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            
            


            //if (m_blurAmountInc > 0 && !m_inc)
            //{
            //    m_blurAmountInc -= (float)gameTime.ElapsedGameTime.TotalSeconds * 0.9f;
            //}
            //else
            //{
            //    m_inc = true;
            //}
            
            m_rippleProgressParam.SetValue(m_rippleProgress);
            m_rippleCoordXParam.SetValue(m_rippleX);
            m_rippleCoordYParam.SetValue(m_rippleY);
            m_angleParam.SetValue(0.005f);

        }

        private void HandleMouseInput(GameTime gameTime)
        {
            MouseState mouseState = Mouse.GetState();
            
            float Xdist = m_bubblzBoard.Launcher.Position.X -  mouseState.X;
            float Ydist = m_bubblzBoard.Launcher.Position.Y - mouseState.Y;

            float angle = (float)Math.Atan2(Ydist, Xdist);
            m_bubblzBoard.Launcher.SetAngle(angle - (float)Math.PI / 2);
            m_cursor.Position = new Vector2(mouseState.X, mouseState.Y);
            m_cursor.Rotation = angle - (float)Math.PI / 2;

            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                m_bubblzBoard.LaunchCurrentBall(new Vector2(mouseState.X, mouseState.Y));
            }

            if (mouseState.RightButton == ButtonState.Pressed)
            {
                m_bubblzBoard.KillAllBubbles();
            }
        }

        private void HandleKeyBoardInput(GameTime time)
        {
            KeyboardState keyboardState = Keyboard.GetState();
            
            if (keyboardState.IsKeyDown (Keys.Left))
            {
                m_bubblzBoard.RotateArrowLeft(time);
            }

            if(keyboardState.IsKeyDown  (Keys.Right))
            {
                m_bubblzBoard.RotateArrowRight(time);
            }

            if (keyboardState.IsKeyDown(Keys.Space))
            {
                m_bubblzBoard.LaunchCurrentBall();
            }
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null ,null , null, m_effects);
            m_bubblzBoard.Draw(gameTime, spriteBatch);
            m_cursor.Draw(gameTime, spriteBatch);
            spriteBatch.End();


            //GraphicsDevice.SetRenderTarget(0, temp);
            //m_shaderTexture = m_shaderRenderTarget.GetTexture();

            
            //m_effects.Begin();
            //m_effects.CurrentTechnique.Passes[4].Begin();            
            //spriteBatch.Draw(m_shaderTexture, Vector2.Zero, Color.White);
            //m_effects.CurrentTechnique.Passes[4].End();            
            //m_effects.End();
            //spriteBatch.End();
            
            base.Draw(gameTime);
        }
    }
}
